#!/usr/bin/env perl
#
# Generate the Zeek file containing the current list of known
# Certificate Transparency logs from the source file provided
# by Google.
#

use 5.14.1;
use strict;
use warnings;

# This is the only kind-of user-configurable line

my $google_log_url = "https://www.gstatic.com/ct/log_list/all_logs_list.json";

# And begin with loading everything we need.
# I was lazy and you probably will have to install a few of these.

use Carp;
use autodie;
use Net::SSLeay;
use HTML::HeadParser;
use LWP::Protocol::https;
use LWP::Simple;
use JSON::Parse qw/parse_json/;
use MIME::Base64;
use Digest::SHA qw/sha256/;

my $google_known_logs_json = get($google_log_url);
croak("Could not get $google_log_url") unless defined($google_known_logs_json);

my $logs = parse_json($google_known_logs_json);

my %operators = map { $_->{id} => $_->{name} } @{$logs->{operators}};

say "#\n# Do not edit this file. This file is automatically generated by gen-ct-list.pl";
say "# File generated at ".localtime;
say "# File generated from ".$google_log_url;
say "#";
say "";
say '@load base/protocols/ssl';
say "module SSL;";
say "redef ct_logs += {";

for my $log (@{$logs->{logs}}) {
	my $desc = $log->{description};
	my $mmd = $log->{maximum_merge_delay};
	my $url = $log->{url};
	my $operator = join(",", map { $operators{$_} } @{$log->{operated_by}});
	my $logid = join('', map {"\\x$_" } unpack("(H2)*", sha256(decode_base64($log->{key}))));
	my $key = join('', map {"\\x$_" } unpack("(H2)*", decode_base64($log->{key})));
	say "[\"$logid\"] = CTInfo(\$description=\"$desc\", \$operator=\"$operator\", \$url=\"$url\", \$maximum_merge_delay=$mmd, \$key=\"$key\"),";
}

say "};";
